package com.microservices.cloud.service.impl;

import com.microservices.cloud.dao.OrderDao;
import com.microservices.cloud.entity.Order;
import com.microservices.cloud.service.AccountService;
import com.microservices.cloud.service.OrderService;
import com.microservices.cloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Resource
    private AccountService accountService;

    @Resource
    private StorageService storageService;


    @Override
    @GlobalTransactional(name = "insertOrder")
    public Integer insertOrder(Order order) {
        log.info("------>开始创建订单");
        Integer orderResult = orderDao.insertOrder(order);

        log.info("------>订单微服务开始调用库存，做扣减");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("------>订单微服务开始调用库存，做扣减end");

        log.info("------>订单微服务开始调用账户，做扣减");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("------>订单微服务开始调用账户，做扣减end");

        log.info("------>修改订单状态");
        orderDao.updateOrder(order.getUserId(), 0);
        log.info("------>修改订单状态end");

        log.info("------>下订单结束了，O(∩_∩)O哈哈~");

        return orderResult;
    }

    @Override
    public Integer updateOrder(Long userId, Integer status) {
        return orderDao.updateOrder(userId, status);
    }
}
